// 用户相关API
import { post, get } from '../utils/request';
import { login as mockLogin, register as mockRegister, getUserInfo as mockGetUserInfo } from '../utils/mockService';
import config from '../config';

// 从配置文件获取是否使用mock数据
const { useMock } = config;

// 登录 - 与Python测试代码中的API路径一致
export const login = async (data) => {
  if (useMock) {
    return mockLogin(data);
  }
  // 添加设备MAC地址
  const loginData = { ...data };
  if (!loginData.device_mac) {
    // 如果没有设备MAC地址，尝试从API获取或使用默认值
    try {
      const { api } = window;
      if (api && api.getMacAddress) {
        loginData.device_mac = await api.getMacAddress();
      } else {
        loginData.device_mac = '00:00:00:00:00:00';
      }
    } catch (error) {
      loginData.device_mac = '00:00:00:00:00:00';
    }
  }
  return post('/token', loginData);
};

// 注册
export const register = async (data) => {
  if (useMock) {
    return mockRegister(data);
  }
  return post('/register', data);
};

// 获取用户信息
export const getUserInfo = async () => {
  if (useMock) {
    return mockGetUserInfo();
  }
  return get('/userinfo');
};

// 退出登录
export const logout = async () => {
  // 清除本地存储的token和用户信息
  localStorage.removeItem('token');
  localStorage.removeItem('userInfo');

  if (useMock) {
    return {
      code: 200,
      message: '退出成功',
      data: null,
    };
  }
  return post('/logout');
};
